package cn.ycxy.lbl.posts.utils;

import cn.ycxy.lbl.common.exception.BusinessException;
import cn.ycxy.lbl.common.exception.enums.ResponseEnum;
import cn.ycxy.lbl.common.pojo.CsAuthenticationInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 使用securitycontext获取user信息
 */
@Slf4j
public class SecurityContextUtils {
    public static CsAuthenticationInfo getUserInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=null;
        if(authentication instanceof UsernamePasswordAuthenticationToken){
            usernamePasswordAuthenticationToken=(UsernamePasswordAuthenticationToken)authentication;
        }else{
            return null;
        }
        Object credentials = usernamePasswordAuthenticationToken.getCredentials();
        log.info("user:{}",credentials);
        return (CsAuthenticationInfo)credentials;
    }

    public static Long getUserId(){
        CsAuthenticationInfo userInfo = getUserInfo();
        if (userInfo==null){
            return 0l;
        }
        if (userInfo instanceof CsAuthenticationInfo){
            log.info("当前认证对象的用户数据是user:{}",userInfo);
            return userInfo.getId();
        }else{
            log.info("当前认证对象的用户数据是:{}",userInfo);
            throw new BusinessException(ResponseEnum.CONFLICT);
        }
    }
}
